#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 文件: email.py
# 说明:
# 时间: 2021/11/07 14:38:22
# 作者: Azure
# 版本: 1.0

'''
email to me
'''

import smtplib
from email.mime.text import MIMEText

from tools.exception import EmailinfoNotfoundError, EmailSendError


class Email(object):
    def __init__(self, userdata: dict) -> None:
        super().__init__()
        self.__userdata = userdata

    def sendtome(self, content: str):
        '''给我发送邮件'''
        userdata = self.__userdata
        try:
            # 基本信息
            mailhost = userdata['mailhost']             # host服务器
            mailuser = userdata['mailuser']             # 登录用户名
            mailpass = userdata['mailpass']             # 登录密码
            mailsender = userdata['mailsender']         # 发件人
            mailreceiver = userdata['mailreceiver']     # 收件人
            mailtiele = userdata['mailtitle']
        except Exception as e:
            raise EmailinfoNotfoundError(f'请检查userdata的信息是否填写完整，错误：{e}')

        message = MIMEText(content, 'plain', 'utf-8')
        message['Subject'] = mailtiele
        message['From'] = mailsender
        message['To'] = mailreceiver

        smtpobj = smtplib.SMTP()
        try:
            smtpobj.connect(mailhost, 25)
            smtpobj.login(mailuser, mailpass)
            smtpobj.sendmail(
                mailsender, mailreceiver, message.as_string()
            )
        except Exception as e:
            raise EmailSendError(f'邮件发送失败，错误：{e}')
